## call to ggplot and the name of the data frame
ggplot(dataframename,
## which variables to use for which plot components
aes(x = column_name, y = column_name)) +
# what type of plot
geom_****() ggplot: Quick Introduction
Welcome
This tutorial allows you to interactively explore R, writing and running code in your web browser. You’ll see above R is being set-up and loading packages right in this browser window.
This tutorial was updated by Brennan Antone using WebR and Quarto. It updates the original ggplot tutorial by Christina Maimone.
This is an Quarto document. Follow the link to learn more about R Markdown and the notebook format used during the workshop.
The cheatsheet is very useful when working with ggplot2.
Setup
This tutorial uses three packages for analysis: dplyr, ggplot2, readr.
We will also use two data sets, one from a package and one built into R.
First, the Palmer Penguins datasets describes physical attributes of individual penguins observed in Antartica.
Second, the New Hampshire Temperature contains average yearly temperature data. This data set is built into R (nhtemp). But we need to put it in a data frame first to make it easier to use (by default, it’s in a special time series object):
Introductions
Why ggplot? For me, it makes exploring my data, especially groups in my data, much easier. I can easily make some plots with ggplot that are difficult enough to make with base R graphics that I just won’t do them routinely when exploring my data. This is bad, because we should visualize our data! I don’t want the code to get in the way of that. ggplot is a package where I recommend first learning the basic syntax, and then go back and learn some more about the theory behind the package – what the logic is to how it works. It took me a few iterations of working with ggplot to get comfortable with it, and to understand how to think in a way that was compatible with how it approaches visualization. But once I did, it made data visualization easier and more fun.
The syntax of ggplot2 is a little bit different than other tidyverse packages, in part because it predates them. But it does share a few things with other tidyverse packages, such as:
- It expects to work with a data frame, and the data frame is the first input
- You can reference the names of columns without quotes or $ syntax
- It’s easy to work with groups in your data
- Instead of functions with lots of different arguments (although some of these functions do have a lot), you combine multiple function calls together to achieve what you want to do
The package is called ggplot2 (there is no first version), the main function in the package is called ggplot, and “ggplot” generally refers to anything with the package (I and others often don’t bother to say the 2 in the package name).
ggplot Basics
Each plot with ggplot has the same template for the code:
The first line says what data and variables to use, and the second line says what type of plot to make. We add the components of the plot together, which is a somewhat unique syntax. By adding a + at the end of each line, we can add more and more components to the plot.
For example:
The warning message is telling you that two observations (rows) in your data frame are not plotted because there were missing values. You can get this warning from explicit missing values or in cases where you set the limits of the axes in a way that excludes some data points.
The first line alone (without the + at the end) makes a plot set up without adding the data:
If we change the geom function we use, the plot type changes:
This is a density plot, where the color of each rectangle indicates how many observations (points on the above plot) fall in that area.
EXERCISE 1
Modify the code. Fill in the ___ to make a line plot using geom_line() with the nh data frame, with year as the x variable and temp as the y:
Different Plot Types
The above plots used two continuous variables. The cheat sheet has the geoms organized by how many and what type of variables you want to plot. For example, we can make a histogram, which is of a single variable:
The warning message is how many bins (bars) there are in the histogram. It defaults to 30, but it wants you to explicitly pick a number instead:
We can also have multiple geoms on the same plot:
EXERCISE 2
Make a histogram (geom_histogram()) of the temp variable in the nh dataset
Other Aesthetics and Grouping
We can set other aesthetics of the plot (color, fill, linetype, marker, etc.) according to variables in our data.
Note that if you want a line or color for each group, those groups need to be defined by a categorical variable. This is the opposite of how data usually needs to be structured when using base R plotting functions. If the values for the two groups are in separate columns in your dataset, you’ll need to reshape your data to get them in a single column instead – something covered in the tidyr session of these workshops.
Each aesthetic – each thing you define in aes() – needs to be a single column in your data set.
With categorical variables, this helps us see the groups in our data:
Note that a legend was added automatically.
method=lm tells it how to fit a line to the data; “lm” means fit a linear model with the lm function. se=FALSE means to not display the standard errors on the plot.
Note that the smoothing was done by group. Specifying color effectively grouped our data, much like what happens with group_by in dplyr.
EXERCISE 3
Repeat the same plot as above, bill_length_mm vs. bill_depth_mm, but color by body_mass_g instead of species.
Labels/Titles
A convenient way to label axes and legends and set the title is with the labs() function, added as a component of the plot:
EXERCISE 4
Plot flipper_length_mm vs. body_mass_g and color by sex. Label the axes and title your plot.
Axis Limits
To change the axes min and max values, like we would with xlim or ylim in base R graphics, we use a scale function and set the limits argument:
Facets
In addition to using color, fill, linetype, etc. to denote groups, we can also make a separate plot for each group, where the plots are aligned and share axes. These are called facets:
The facet function syntax is using the formula syntax used elsewhere in R, but it can be tough to remember. It’s on the cheat sheet though so you can look it up. There are other options for laying out plots horizontally or in a grid.
Note that the plots share an x-axis, and the y-axis has the same range in each plot.
If you want to put multiple plots in a single image together, but they are not facets of a single plot, see the patchwork package.
EXERCISE 5
Make a histogram (set a value for bins) of body_mass_g for each species:
Styling
Themes control the look of the plot not related to the data: fonts, backgrounds, grid lines, axis lines, etc.
There are some built-in themes (theme_minimal(), theme_bw(), theme_classic(), etc.), but you can also control the styling further with the theme() function:
For further control, use theme instead or in addition:
Many theme elements are controlled by setting options in additional element functions:
element_blank()- omit the elementelement_text()element_line()element_rect()
These are options that you will generally google for how to do: “ggplot remove gridlines”, “ggplot change font size”, etc.
In addition to themes, you can control some aspects of the data-driven elements of the plot directly, without using a variable to define them. For example with color or size, if we specify them outside of a call to aes() within the geom function:
it colors all of the points the same color.
EXERCISE 6
Change the fill color for the bars in our histogram above to be “darkgreen”. The code from above is copied below to get you started.
Pipes
We use +, not %>%, to join together components of our ggplot. But we can still pipe the results of other commands into ggplot - I just didn’t above because we were just plotting the data frame as it is. For example, to plot only the Adelie penguins:
Learn More
More documentation is available at the ggplot2 website.
The cheatsheet is very useful when working with ggplot2.